package com.shiwaixiangcun.monitor.security;

import com.shiwaixiangcun.monitor.utils.MsConstants;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityAuditorAware implements AuditorAware<Long> {

    @Override
    public Long getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            return MsConstants.DEFAULT_CREATE_BY;
        }

        MsUserDetails userDetails = (MsUserDetails) authentication.getPrincipal();
        return userDetails.getUser().getId();
    }

}
